package com.carhome.ui.fagment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.carhome.R;
import com.carhome.adapter.ArticleFragment1ListAdapter;
import com.carhome.adapter.ArticleFragmentHeadViewAdapter;
import com.carhome.bean.ArticleNewsInfo;
import com.carhome.bean.json.ArticleFragment1Focusimg;
import com.carhome.bean.json.ArticleFragment1Headlineinfo;
import com.carhome.bean.json.ArticleFragment1ListJson;
import com.carhome.bean.json.ArticleFragment1News;
import com.carhome.bean.json.ArticleFragment1Result;
import com.carhome.bean.json.ArticleFragment1Topnewsinfo;
import com.carhome.ui.base.BaseFragment;
import com.carhome.utils.HttpJsonCache;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.graphics.AvoidXfermode.Mode;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.FileObserver;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

public class ArticleFragmentNewest extends Fragment {

	private PullToRefreshListView mListView; // 定义带下拉刷新的listview控件
	private HttpUtils mHttpUtils;
	private View mainView; // 解析布局
	private View headView;

	private List<ArticleNewsInfo> listDatas; // listview数据集合
	private List<ArticleNewsInfo> listHeadDatas; // listview head数据集合
	private ArticleFragment1ListAdapter listAdapter; // listview适配器
	ArticleFragmentHeadViewAdapter listHeadAdapter; // listviewHead 适配器
	private int pageIndex; // listview分页加载页码

	private boolean isDropDown = true; // 判断listview是下拉刷新还是向上加载更多

	private String urlPath = "http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt0-p1-s20-l0.html";

	HttpJsonCache httpJsonCache;
	ListView actualListView; // 从PullToRefreshListView控件中获取实际的listview

	private ViewPager headViewPager;
	private LinearLayout listviewheadIndicator;
	private int autoChangeTime = 3000;
	private ImageView dot, dots[];
	private Runnable runnable;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.article_fragment_newset, container, false);
		initViews();
		return mainView;
	}

	private void initViews() {

		mListView = (PullToRefreshListView) mainView
				.findViewById(R.id.article_fragment_newset_list_view);
		// 设置下拉监听
		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				isDropDown = true;
				mHttpUtils.send(HttpMethod.GET, urlPath, callBack);
			}
		});

		mListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			public void onLastItemVisible() {
				pageIndex++;
				String currentPageUrl = urlPath.replaceAll("(-p\\d+-)", "-p" + pageIndex + "-");
				System.out.println(currentPageUrl);
				mHttpUtils.send(HttpMethod.GET, currentPageUrl, callBack);
			}
		});

		// 设置底部上拉加载更多监听
		/*
		 * mListView.setOnBottomListener(new OnClickListener() { public void
		 * onClick(View v) { pageIndex++; String currentPageUrl =
		 * urlPath.replaceAll("(-p\\d+-)", "-p" + pageIndex + "-");
		 * System.out.println(currentPageUrl); mHttpUtils.send(HttpMethod.GET,
		 * currentPageUrl, callBack); } });
		 */
		// mListView.setShowFooterWhenNoMore(true);

		mHttpUtils = new HttpUtils(1000);

		listDatas = new ArrayList<ArticleNewsInfo>();
		listHeadDatas = new ArrayList<ArticleNewsInfo>();

		listAdapter = new ArticleFragment1ListAdapter(getActivity());

		httpJsonCache = new HttpJsonCache(getActivity());
		String json = httpJsonCache.getJsonCache(urlPath);
		System.out.println("json ++++ :" + json);

		headView = getActivity().getLayoutInflater().inflate(
				R.layout.article_fragment_listview_headview, null);// 解析Listview的headView的布局

		actualListView = mListView.getRefreshableView();
		initHeadViewPager();

		// mHttpUtils.send(HttpMethod.GET, urlPath, callBack);
		// mListView.addView(getActivity().getLayoutInflater().inflate(R.layout.article_fragment_listview_headview,
		// mListView));
		if (json != null) {
			setupData(json);
		}
	}

	// 初始化listview head头的信息
	private void initHeadViewPager() {
		listHeadAdapter = new ArticleFragmentHeadViewAdapter(getActivity());
		headViewPager = (ViewPager) headView
				.findViewById(R.id.article_fragment_listview_head_viewpager);
		mHttpUtils.send(HttpMethod.GET, urlPath, callBack);

	}

	private RequestCallBack<String> callBack = new RequestCallBack<String>() {
		public void onFailure(HttpException arg0, String arg1) {
			System.out.println("request timeout");
			if (isDropDown) {
				mListView.onRefreshComplete();
			} else {
				Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
			}
		}

		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result.toString();
			setupData(json);
		}

	};
	private boolean isFirstEnter = true;

	private void setupData(String json) {
		ArticleFragment1ListJson mArticleFragment1ListJson = JSON.parseObject(json,
				ArticleFragment1ListJson.class);
		ArticleFragment1Result result = mArticleFragment1ListJson.getResult();
		ArticleFragment1Topnewsinfo topnewsinfo = result.getArticleFragment1Topnewsinfo();
		ArticleFragment1Headlineinfo headlineinfo = mArticleFragment1ListJson.getResult()
				.getArticleFragment1Headlineinfo();
		List<ArticleFragment1News> newslist = mArticleFragment1ListJson.getResult().getNewslist();
		List<ArticleFragment1Focusimg> focusing = mArticleFragment1ListJson.getResult()
				.getFocusimg();

		listHeadDatas.clear();
		for (Iterator iterator = focusing.iterator(); iterator.hasNext();) {
			ArticleFragment1Focusimg articleFragment1Focusimg = (ArticleFragment1Focusimg) iterator
					.next();
			ArticleNewsInfo focuingNews = new ArticleNewsInfo();
			focuingNews.setDataFromFocuingNews(articleFragment1Focusimg);
			listHeadDatas.add(focuingNews);
		}

		listDatas.clear();
		for (Iterator iterator = newslist.iterator(); iterator.hasNext();) {
			ArticleFragment1News news = (ArticleFragment1News) iterator.next();
			ArticleNewsInfo newsInfo = new ArticleNewsInfo();
			newsInfo.setDataFromNews(news);
			listDatas.add(newsInfo);
		}

		if (isDropDown) {
			listHeadAdapter.setupData(listHeadDatas);
			listHeadAdapter.notifyDataSetChanged();
			headViewPager.setAdapter(listHeadAdapter);

			headViewPager.setOnPageChangeListener(myListHeadChangeListener);
			if (isFirstEnter) {
				initDot();
			}

			runnable = new Runnable() {
				@Override
				public void run() {
					int next = headViewPager.getCurrentItem() + 1;
					if (next >= listHeadAdapter.getCount()) {
						next = 0;
					}
					viewHandler.sendEmptyMessage(next);
				}
			};
			viewHandler.postDelayed(runnable, autoChangeTime);

			listAdapter.removeAll();
			listAdapter.setData(listDatas);
			listAdapter.notifyDataSetChanged();

			if (isFirstEnter) {
				actualListView.addHeaderView(headView);
				mListView.setAdapter(listAdapter);
				isFirstEnter = false;
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
			mListView.getLoadingLayoutProxy().setLastUpdatedLabel(
					"更新完成" + dateFormat.format(new Date()));
			mListView.onRefreshComplete();
			httpJsonCache.savaJsonCache(urlPath, json);
			isDropDown = false;
		} else {
			System.out.println("bottomcomplete");
			listAdapter.setData(listDatas);
			listAdapter.notifyDataSetChanged();
			// mListView.setAdapter(listAdapter);
		}
	}

	// 初始化dot视图
	private void initDot() {
		listviewheadIndicator = (LinearLayout) headView
				.findViewById(R.id.article_fragment_listview_head_indicatorView);

		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(40, 40);
		layoutParams.setMargins(4, 3, 4, 3);

		dots = new ImageView[listHeadAdapter.getCount()];
		for (int i = 0; i < listHeadAdapter.getCount(); i++) {
			dot = new ImageView(getActivity());

			dot.setLayoutParams(layoutParams);
			dots[i] = dot;
			dots[i].setTag(i);
			// dots[i].setOnClickListener(onClick);

			if (i == 0) {
				dots[i].setBackgroundResource(R.drawable.dotc);
			} else {
				dots[i].setBackgroundResource(R.drawable.dotn);
			}

			listviewheadIndicator.addView(dots[i]);
		}
	}

	OnPageChangeListener myListHeadChangeListener = new OnPageChangeListener() {

		public void onPageSelected(int position) {
			setCurDot(position);
			viewHandler.removeCallbacks(runnable);
			viewHandler.postDelayed(runnable, autoChangeTime);
		}

		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		}

		public void onPageScrollStateChanged(int state) {
		}
	};
	/**
	 * 每隔固定时间切换广告栏图片
	 */
	private final Handler viewHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			setCurView(msg.what);
		}
	};

	/**
	 * 设置当前的引导页
	 */
	private void setCurView(int position) {
		if (position < 0 || position > listHeadAdapter.getCount()) {
			return;
		}
		headViewPager.setCurrentItem(position);
	}

	/**
	 * 选中当前引导小点
	 */
	private void setCurDot(int position) {
		for (int i = 0; i < dots.length; i++) {
			if (position == i) {
				dots[i].setBackgroundResource(R.drawable.dotc);
			} else {
				dots[i].setBackgroundResource(R.drawable.dotn);
			}
		}
	}
}
